#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import cookielib
import types
        
from lixian_api import LiXianAPI

import FileHostProtoType
 
COOKIEJAR_CLASS = cookielib.MozillaCookieJar    

class kcitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class kuaichuan(FileHostProtoType.FileHostProcess):     
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "Xunlei Kuaichuan" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.isanoy = False
        self.logtype = 'poster'
        self._cookieCurl = '%s_%s.cookie' % (self._user, self.hostname)
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
       
        self._xunlei = LiXianAPI()
        self._cj = COOKIEJAR_CLASS(self._cookieCurl)
        self.session = self._xunlei.session
        # self.session.headers['User-Agent'] = 'Shockwave Flash'
#        self.session.cookies = self._cj
        if self.proxy:
            self.session.proxies = {'http', self.proxy}
        
        
    def login(self):
        '''
        login to TurboBit
        return opener object which includes cookies
        '''
        self.generateOpener()
#        
        if self.restore_cookiejar(): 
            self.fherr.write("User %s logined." % self._user)
            return True
        
        self.fherr.write('login to %s %s/%s...' % (self.hostname, self._user,'*'*len(self._pwd)))
        
        self.islogin = self._xunlei.login(self._user, self._pwd)
        #post login request
        if not self.islogin:
            self.fherr.write("User %s Failed to Login %s." % (self._user, self.hostname))
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True        

        if type(self.session.cookies) == type({}):
            items = self.session.cookies.items()
        else:
            items = [(cookie.name, cookie.value) for cookie in self.session.cookies]
        for item in items:
            ck = cookielib.Cookie(version=0, 
                                  name=item[0], 
                                  value=item[1], 
                                  port=None, 
                                  port_specified=False, 
                                  domain='.xunlei.com', 
                                  domain_specified=True, 
                                  domain_initial_dot=True, 
                                  path='/', 
                                  path_specified=True, 
                                  secure=False, 
                                  expires='1600000000', 
                                  discard=False, 
                                  comment=None, 
                                  comment_url=None, 
                                  rest={})
            self._cj.set_cookie(ck)
        self._cj.save(ignore_discard=True)
        return True
    
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(ignore_discard=True) 
                for cookie in self._cj:
                    # print cookie.name, cookie.value
                    self.session.cookies[cookie.name] = cookie.value
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to confirm cookie is avaiable
            return self._xunlei.check_login()
        return False
        
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        return self.upload_web_local_register(file, progressLog, other_args, send_range)
    
    UPLOAD_INFO_REQURL = "http://kuai.xunlei.com/webfilemail_interface?action=webfilemail_upload_check&recver_email=&msg=&cachetime=%s&files=%s,%d"         
    def upload_web_local_register(self, file, progressLog=None, other_args=None, send_range=None):  
        self.session.get("http://kuai.xunlei.com/upload")
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        url = self.UPLOAD_INFO_REQURL %(self.get_timeticket(), filename, filesize)
        print url 
        r = self._xunlei.session.get(url)
        upload_infos = json.loads(r.content)
        assert upload_infos["result"] == 0, "Failed to get upload infos. %s" % upload_infos
            
        res_id = upload_infos["msg"][0]["res_id"]
        post_url = upload_infos["msg"][0]["post_url"]
        post_key = upload_infos["msg"][0]["post_key"]
        task_id = upload_infos["msg"][0]["task_id"]
        download_url = upload_infos["msg"][0]["download_url"]
        
        self.fherr.write(info) 
        fileobj = open(file, 'rb')
        fileobj.seek(start_point)  
        data = {'Filedata' : fileobj,
                'Filename' : filename,
                'post_key' : post_key,
                'file_size' : filesize,
                'res_id' : res_id,
                'uid' : self._xunlei.uid,
                'task_id' : task_id,
                'Upload' : 'Submit Query'}
        
        uploadurl = post_url
        upload_response = self.post_request(uploadurl, data, retry=1,\
                                            cb=callback, \
                                            setfilename=filename,\
                                            setfilesize=filesize)
        
        assert "result=0" in upload_response, "Failed. Not expected upload response: %s" % upload_response
        basename = os.path.basename(file) 
        item = kcitem(basename, 'file', 
                      '', 
                      download_url, 
                      filename)
        self.newupload.append(item)  
        return item 
            